import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
} from 'typeorm';

/**
 * 会话实体 - 用于管理聊天会话
 */
@Entity('conversations')
@Index(['user1Id', 'user2Id'], { unique: true }) // 确保两个用户之间只有一个会话
export class Conversation {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({
    comment: '会话ID（由较小的userId和较大的userId组合生成）',
    unique: true,
  })
  conversationId: string;

  @Column({ comment: '用户1的ID（较小的ID）' })
  @Index()
  user1Id: number;

  @Column({ comment: '用户2的ID（较大的ID）' })
  @Index()
  user2Id: number;

  @Column({ type: 'text', nullable: true, comment: '最后一条消息内容' })
  lastMessageContent: string | null;

  @Column({ type: 'timestamp', nullable: true, comment: '最后一条消息时间' })
  lastMessageAt: Date | null;

  @Column({ default: 0, comment: '用户1的未读消息数' })
  user1UnreadCount: number;

  @Column({ default: 0, comment: '用户2的未读消息数' })
  user2UnreadCount: number;

  @CreateDateColumn({ type: 'timestamp', comment: '创建时间' })
  createdAt: Date;

  @UpdateDateColumn({ type: 'timestamp', comment: '更新时间' })
  updatedAt: Date;

  /**
   * 生成会话ID
   * @param userId1 用户1的ID
   * @param userId2 用户2的ID
   * @returns 会话ID
   */
  static generateConversationId(userId1: number, userId2: number): string {
    const [smallerId, largerId] =
      userId1 < userId2 ? [userId1, userId2] : [userId2, userId1];
    return `${smallerId}_${largerId}`;
  }
}
